﻿using System;
using System.IO;
using System.Net;
using BluePortal.Framework;
using BluePortal.Medias.Core;

namespace BluePortal.Encoding.Core.Providers
{
    /// <summary>
    /// Upload a file on an ftp site.
    /// Connection String format : UploadFtpRootDirectory=<>;FtpLogin=<>;FtpPassword=<>;VideosUrl=<>
    /// </summary>
    public class FtpUploadService : BaseUploadService, IVideoUploadService
    {
        #region IVideoUploadService Members

        BCVideo bc = new BCVideo();

        public void Upload(Video video, string directory)
        {
            try
            {
                string FtpLogin = ConnectionParameters["FtpLogin"];
                string FtpPassword = ConnectionParameters["FtpPassword"];
                string UploadFtpRootDirectory = ConnectionParameters["UploadFtpRootDirectory"];
                string baseDir = Concat(UploadFtpRootDirectory, video.ID.ToString());

                FtpWebRequest request;
                NetworkCredential credentials = new NetworkCredential(FtpLogin, FtpPassword);

                //create directory                    
                Uri fileUri = new Uri(directory);
                request = (FtpWebRequest)WebRequest.Create(fileUri);
                request.Method = WebRequestMethods.Ftp.MakeDirectory;
                request.Credentials = credentials;
                request.GetResponse();

                foreach (string file in GetFiles(directory))
                {
                    fileUri = new Uri(Concat(baseDir, Path.GetFileName(file)));
                    request = (FtpWebRequest)WebRequest.Create(fileUri);
                    request.Method = WebRequestMethods.Ftp.UploadFile;
                    request.Credentials = credentials;

                    Stream stm = request.GetRequestStream();
                    using (Stream source = File.OpenRead(file))
                    {
                        Utils.CopyStream(source, stm, 0x2000);
                    }
                    stm.Close();
                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                    Log.LogInfo("FtpUploadService", "UploadFile", string.Format("upload status {0} :{1}", file, response.StatusDescription));
                }

                video.ProviderOptions = ConnectionParameters["VideosUrl"];
            }
            catch (Exception ex)
            {
                Log.LogError("FtpUploadService", "UploadFile", ex);
            }
        }

        private string Concat(string url, string suburl)
        {
            if (!url.EndsWith("/"))
                url += "/";
            url += suburl;
            return url;
        }

        public override string GetUrlFromVID(Guid vid)
        {
            base.GetUrlFromVID(vid);
            Video v = bc.FindVideoByID(vid);

            return Concat(v.ProviderOptions, vid.ToString() + "/" + vid.ToString() + ".wmv");
        }
        public override string GetUrlFromVID(Guid vid, int formatId)
        {
            if (formatId == 0)
            {
                return GetUrlFromVID(vid);
            }
            else
            {
                base.GetUrlFromVID(vid, formatId);
                Video v = bc.FindVideoByID(vid);
                return Concat(v.ProviderOptions, vid.ToString() + "/" + vid.ToString() + "_" + formatId.ToString() + ".wmv");
            }
        }


        public void Delete(Guid vid)
        {
            //TODO
        }

        #endregion
    }
}
